package com.example.backend.controller;

import com.example.backend.model.Goods;
import com.example.backend.service.GoodsService;
import com.example.backend.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    GoodsService service;

    @GetMapping
    public Response<List<Goods>> findAll(@RequestBody(required = false) Map<String, String> params) {
        // params: name, typename
        List<Goods> data =  service.findWith(params);
        return Response.Ok(
                "all goods",
                data
        );
    }

    @GetMapping("/{id}")
    public Response<Goods> findOne(@PathVariable("id") Integer id) {
        Goods goods = service.findOne(id);
        return Response.Ok(
                "goods",
                goods
        );
    }
    @PostMapping
    public Response<Integer> insertGoods(@RequestBody Goods goods) {
        int result = service.insertOne(goods);
        if(result != -1) {
            return Response.Ok("insert sucess", result);
        } else {
            return Response.Error("insert failed", result);
        }
    }

    @PutMapping
    public Response<Integer> updateGoods(@RequestBody Goods goods) {
        int result = service.updateOne(goods);
        if(result != -1 ) {
            return Response.Ok("update success", result);
        } else {
            return Response.Error("update failed", result);
        }
    }

    @DeleteMapping
    public Response<Integer> deleteGoods(@RequestParam("id") int id) {
        int result = service.deleteOne(id);
        if(result != -1) {
            return Response.Ok("delete success", result);
        } else {
            return Response.Error("delete failed", result);
        }
    }
}
